import axios from 'axios'

const API_KEY = '#'
const BASE_URL = '#'

const aiClient = axios.create({
  baseURL: BASE_URL,
  headers: {
    'Authorization': `Bearer ${API_KEY}`,
    'Content-Type': 'application/json'
  }
})

export const chatWithAI = async (messages, onProgress) => {
  try {
    const response = await aiClient.post('chat/completions', {
      model: '',
      messages: messages,
      temperature: 0.7,
      max_tokens: 1000,
      presence_penalty: 0.6,
      frequency_penalty: 0.3,
      stream: true // 启用流式响应
    }, {
      responseType: 'stream',
      onDownloadProgress: (progressEvent) => {
        const chunk = progressEvent.event.target.response
        if (chunk) {
          const lines = chunk.split('\n')
          lines.forEach(line => {
            if (line.startsWith('data: ') && line !== 'data: [DONE]') {
              try {
                const data = JSON.parse(line.slice(6))
                const content = data.choices[0]?.delta?.content
                if (content) {
                  onProgress(content)
                }
              } catch (e) {
                console.error('Parse chunk error:', e)
              }
            }
          })
        }
      }
    })

    return { content: '' } // 实际内容会通过 onProgress 回调传递
  } catch (error) {
    console.error('AI API Error:', error.response || error)
    throw new Error(error.response?.data?.error?.message || 'AI service error')
  }
} 